package com.donger.business.modules.upms.handler;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.donger.business.constant.Constants;
import com.donger.business.enums.LoginTypeEnum;
import com.donger.business.modules.upms.entity.SysSocialDetails;
import com.donger.business.modules.upms.entity.SysUser;
import com.donger.business.modules.upms.mapper.SysSocialDetailsMapper;
import com.donger.business.modules.upms.service.ISysUserService;
import com.donger.business.utils.DingUtils;
import com.donger.common.core.constant.SecurityConstants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;

@Component("DINGDING")
@AllArgsConstructor
@Slf4j
public class DingLoginHandler extends AbstractLoginHandler {
    private final SysSocialDetailsMapper sysSocialDetailsMapper;
    private final ISysUserService sysUserService;


    @Override
    public String identify(String code) {
        SysSocialDetails condition = new SysSocialDetails();
        condition.setType(LoginTypeEnum.DING.getType());

        SysSocialDetails socialDetails = sysSocialDetailsMapper.selectOne(new QueryWrapper<>(condition));


        String timestamp = String.valueOf(new Date().getTime());
        String url = String.format(Constants.DING_AUTHORIZATION_CODE_URL
                , socialDetails.getAppId(),timestamp, DingUtils.getSignature(socialDetails.getAppSecret(),timestamp));
        HashMap<String, Object> objectObjectHashMap = new HashMap<>(0);
        objectObjectHashMap.put("tmp_auth_code",code);
        String result = HttpRequest.post(url)
                .body(JSONUtil.parse(objectObjectHashMap))
                .execute().body();
        log.debug("钉钉响应报文:{}", result);

        return JSONUtil.parseObj(result).getJSONObject("user_info").getStr("openid");
    }

    @Override
    public SysUser info(String identify) {
        SysUser user = sysUserService
                .getOne(Wrappers.<SysUser>query()
                        .lambda().eq(SysUser::getDingId, identify));

        if (user == null) {
            log.error("钉钉未绑定:{}", identify);
            return null;
        }
        return user;
    }
}
